package hz.mobileproject.pda.toolsmanager.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.activity.CaptureActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.entity.request.Rq_queryTools;
import hz.mobileproject.pda.entity.request.Rq_toolCalling;
import hz.mobileproject.pda.entity.request.Rq_toolEnd;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Rp_queryTool;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.adapter.ToolsInventoryAdapter;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.CommonUtil;
import hz.mobileproject.pda.utils.HttpRqUtils;

import static com.google.zxing.activity.CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN;

/**
 * Created by hasee on 2017/11/16.
 * 工具清点
 */
public class ToolsInventoryActivity extends AppCompatActivity implements IShowBarcodeStr, View.OnClickListener{
    private ListView mListView;
    private Button mBtInput;
    private ImageButton mIbShowInput;
    private LinearLayout mLlInput;
    private EditText mEtInput;
    private LoadingDialog mUpDialog;
    private Button mBtnEnd;
    private Button mBtnStart;

    private ToolsInventoryAdapter mAdapter;
    private List<Rp_queryTool> mList = new ArrayList<>();
    private HandleBroadcast mHandleBroadcast;
    private SoundPool mSoundPool;
    private int mSoundId;
    private Gson mGson;
    private Response_loadPoliceInfo mPoliceInfo;
    private String mCheckId;
    //检查选项
    private String[] mFinishTypeStr;
    //当前清点index
    private int mCallingIndex;

    //扫描成功返回码
    private static final int REQUEST_CODE_TOOLS = 666;
    public static final int RESULT_CODE_QR_SCAN = 0xA1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tools_inventory);
        initView();
        initData();
        initThings();
    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.lv_tools_inventory);
        mBtInput = (Button) findViewById(R.id.bt_tools_input);
        mIbShowInput = (ImageButton) findViewById(R.id.ib_tools_show_input);
        mLlInput = (LinearLayout) findViewById(R.id.ll_tools_input);
        mEtInput = (EditText) findViewById(R.id.et_tools_input);
        mBtnEnd = (Button) findViewById(R.id.btn_end_inventory);
        mBtnStart = (Button) findViewById(R.id.btn_start_inventory);
        mLlInput.setVisibility(View.GONE);
    }

    private void initData() {
        mGson = new Gson();
        mUpDialog = new LoadingDialog(this);
        mFinishTypeStr = new String[]{"正常","异常"};
        mAdapter = new ToolsInventoryAdapter(this, mList);
        mListView.setAdapter(mAdapter);
        mCheckId = getIntent().getStringExtra("mCheckId");
        mPoliceInfo = getIntent().getParcelableExtra("mPoliceInfo");

        //从接口获得清点列表
        Rq_queryTools queryTools = new Rq_queryTools();
        queryTools.setCheck_id(mCheckId);
        queryTools.setCus_number(mPoliceInfo.getCus_number()+"");
        queryTools.setDept_id(mPoliceInfo.getDepartment_id()+"");
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_QUERY_CALL_LIST,queryTools,querryCallBack);
    }

    private void initThings() {
        mBtInput.setOnClickListener(this);
        mBtnEnd.setOnClickListener(this);
        mBtnStart.setOnClickListener(this);
        mIbShowInput.setOnClickListener(this);
    }


    /**
     * 初始化条形码扫描
     */
    private void initScan() {
        if(Constance.isNeiMeng) {  //如果是演示版本则打开相机扫描
            //打开二维码扫描界面
            if(CommonUtil.isCameraCanUse()){
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_TOOLS);
            }else{
                Toast.makeText(this,"请打开此应用的摄像头权限！",Toast.LENGTH_SHORT).show();
            }
        }else{
            mUpDialog.setMessage("请扫工具条形码").show();
            mHandleBroadcast = new HandleBroadcast(this, this);
            mSoundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
            mSoundId = mSoundPool.load("/etc/Scan_new.ogg", 1);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_tools_show_input://隐藏显示手动清点框
                if(mLlInput.getVisibility() == View.VISIBLE){
                    mLlInput.setVisibility(View.GONE);
                }else{
                    mLlInput.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.bt_tools_input://手动清点按钮
                String assetCode = mEtInput.getText().toString();
                calling(assetCode);
                break;

            case R.id.btn_end_inventory://手动结束清点
                if(StringUtils.isEmpty(mCheckId) || mPoliceInfo == null){
                    ToastUtils.showLong("未获取到检查数据");
                    return;
                }
                Rq_toolEnd toolEnd = new Rq_toolEnd();
                toolEnd.setCheck_id(mCheckId);
                toolEnd.setCus_number(mPoliceInfo.getCus_number()+"");
                toolEnd.setTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
                HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_END,toolEnd,endInventoryCallBak);
                break;
            case R.id.btn_start_inventory:
                initScan();
                break;
        }
    }

    @Override
    public void updateText(String msg) {
        if(!mUpDialog.isShowing()){
            return;
        }
        mSoundPool.play(mSoundId, 1, 1, 0, 0, 1);
        mUpDialog.dismiss();
        calling(msg);
    }
    /**
     * 摄像头扫描条码返回
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if(resultCode != RESULT_CODE_QR_SCAN){
            return;
        }
        if(requestCode == REQUEST_CODE_TOOLS){//扫描工具条码返回
            calling(data.getStringExtra(INTENT_EXTRA_KEY_QR_SCAN));
        }
    }


    /**
     * 加载列表回调
     */
    private CustomNetCallBack querryCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            List<Rp_queryTool> listdata = mGson.fromJson(data,new TypeToken<ArrayList<Rp_queryTool>>() {}.getType());
            mAdapter.clearAdd(listdata);

        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("加载列表失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("加载列表失败");
            LogUtils.e(ex);
        }
    };

    /**
     * 清点方法
     * @param assetCode
     */
    private void calling(String assetCode){
        //在列表中搜索
        mCallingIndex = -1;
        for (int i=mList.size()-1; i>=0;i--){
            if (assetCode.equals(mList.get(i).getAsset_code())){
                mCallingIndex = i;
                break;
            }
        }
        if(mCallingIndex<0){
            ToastUtils.showLong("没有该编码的物品");
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(ToolsInventoryActivity.this);
        builder.setItems(mFinishTypeStr, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Rp_queryTool tempData = mAdapter.getListData().get(mCallingIndex);
                Rq_toolCalling toolCalling = new Rq_toolCalling();
                toolCalling.setCheck_id(mCheckId);
                toolCalling.setCus_number(mPoliceInfo.getCus_number()+"");
                toolCalling.setPolice_id(mPoliceInfo.getPolice_id());
                toolCalling.setAsset_code(tempData.getAsset_code());
                toolCalling.setCondition(mFinishTypeStr[which]);
                toolCalling.setTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
                Rq_toolCalling[] toolCallings = new Rq_toolCalling[]{toolCalling};
                //调取清点接口
                HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_CALLING, toolCallings , callingCallBack);
            }
        });
        builder.create().show();
    }

    /**
     * 清点接口回调
     */
    private CustomNetCallBack callingCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            ToastUtils.showLong("清点成功");
            mAdapter.deleteOne(mCallingIndex);
            if(mAdapter.getCount() <= 0){
                //当列表没有清点的了结束清点
                Rq_toolEnd toolEnd = new Rq_toolEnd();
                toolEnd.setCheck_id(mCheckId);
                toolEnd.setCus_number(mPoliceInfo.getCus_number()+"");
                toolEnd.setTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
                HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_END,toolEnd,endInventoryCallBak);
            }
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("清点失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("清点失败");
        }
    };

    /**
     * 结束清点接口回调
     */
    private CustomNetCallBack endInventoryCallBak = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            AlertDialog.Builder builder = new AlertDialog.Builder(ToolsInventoryActivity.this);
            builder.setTitle("提示");
            builder.setMessage("清点结束成功，即将关闭本界面");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }).setCancelable(false).create().show();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("清点结束失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("清点结束失败");
            LogUtils.e(ex);
        }
    };

}